<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="80px"
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        label="供应商名"
        prop="name"
      >
        <el-input v-model="dataForm.name" />
      </el-form-item>
      <el-form-item
        label="商品sku"
        prop="sku"
      >
      <el-input v-model="dataForm.sku" />
      </el-form-item>
      <el-form-item
        label="代码"
        prop="code"
      >
      <el-input v-model="dataForm.code" />
      </el-form-item>
      <el-form-item
        label="单价"
        prop="price"
      >
      <el-input-number v-model="dataForm.price" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button
          @click="visible = false"
        >取消</el-button>
        <el-button

          type="primary"
          @click="onSubmit()"
        >确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { Debounce } from '@/utils/debounce'
const emit = defineEmits(['refreshDataList'])
const visible = ref(false)
const contentEnRef = ref(null)

const dataRule = {
  name: [
    { required: true, message: '供应商名不能为空', trigger: 'blur' },
  ],
  sku: [
    { required: true, message: '商品SKU不能为空', trigger: 'blur' },
  ]
}

const dataForm = ref({});
const dataFormRef = ref(null)
const init = (id) => {
  dataForm.value.id = id || 0
  visible.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
    if (dataForm.value.id) {
      http({
        url: http.adornUrl('/admin/supplier/queryById'),
        method: 'get',
        params: http.adornParams({id: dataForm.value.id})
      })
        .then(({ data }) => {
          dataForm.value = data
        })
    }
  })
}
defineExpose({ init })

/**
 * 表单提交
 */
const onSubmit = Debounce(() => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      http({
        url: http.adornUrl('/admin/supplier/addOrUpd'),
        method: 'post',
        data: http.adornData(dataForm.value)
      })
        .then(() => {
          ElMessage({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              visible.value = false
              emit('refreshDataList')
              dataForm.value.content = ''
            }
          })
        })
    }
  })
})

</script>
